const {database} = require("@common/config")

class indexService{
  async getDynamicList(offset ,pageSize){
    try {
      const statement = `SELECT 
      dt.id,dt.title,dt.images,dt.user_id,dt.createAt,dt.updateAt,
      JSON_OBJECT('id',u.id,'phone',u.phone,'createAt',u.createAt,'avatar',u.avatar,'updateAt',u.updateAt) as userInfo,
      (SELECT COUNT(*) FROM wx_likes_dynamic WHERE wx_likes_dynamic.dynamic_id = dt.id) as likes,
      IF(COUNT(dtl.id),
       JSON_ARRAYAGG(JSON_OBJECT('id',dtl.id,'user_id',dtl.user_id,'dynamic_id',dtl.dynamic_id,'createAt',dtl.createAt,'updateAt',dtl.updateAt)),
       JSON_ARRAY()) as likesList
        FROM wx_dynamic as dt 
        INNER JOIN wx_user as u ON u.id = dt.user_id
        LEFT JOIN wx_likes_dynamic as dtl ON dtl.dynamic_id = dt.id
        GROUP BY dt.id
        ORDER BY dt.updateAt DESC
        LIMIT ?,?
        `
      const [result] = await database.promise().execute(statement,[offset + '',pageSize + ''])
      return result
    } catch (err) {
      throw new Error(err)
    }
  }

  async getDynamicListTotalSize(){
    try {
      const statement = `SELECT COUNT(*) as totalSize FROM wx_dynamic`
      const [[result]] = await database.promise().execute(statement)
      return result
    } catch (err) {
      throw new Error(err)
    }
  }

  async putDynamic(title,images,user_id,topic_id){
    try{
     const statement =  `INSERT INTO wx_dynamic (title,images,user_id,topic_id) VALUES (?,?,?,?)`
     const [result] = await database.promise().execute(statement,[title,images,user_id,topic_id])
     if(result?.affectedRows === 1){
      return result
     }
     return result
    }catch (err) {
      throw new Error(err)
    }
  }

  async putDynamicLikes(dynamicId,userId){
    try {
      const statement = `INSERT INTO wx_likes_dynamic (dynamic_id,user_id) VALUES (?,?)`
      const [result] = await database.promise().execute(statement,[dynamicId,userId])
      return result
    } catch (error) {
      throw new Error(error)
    }
  }

  async delDynamicLikes(dynamicId,userId){
    try {
      const statement = `DELETE FROM wx_likes_dynamic WHERE dynamic_id = ? AND user_id = ?`
      const [result] = await database.promise().execute(statement,[dynamicId,userId])
      return result

    } catch (error) {
      throw new Error(error)
    }
  }

  async getDynamicLikesTotalSize(dynamicId){
    try {
      const statement = `SELECT COUNT(*) as likes FROM wx_likes_dynamic WHERE dynamic_id = ?`
      const [result] = await database.promise().execute(statement,[dynamicId])
      return result[0].likes

    } catch (error) {
      throw new Error(error)
    }
  }

  async getDynamicLikesList(dynamicId){
    try {
      const statement = `SELECT * FROM wx_likes_dynamic WHERE dynamic_id = ?`
      const [result] = await database.promise().execute(statement,[dynamicId])
      return result

    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new indexService()